package com.ywc.tools.communica;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Random;

public class SocketService extends Service{

    private boolean isrun=false;
    private class SocketThread implements Runnable {

        @Override
        public void run() {
            ServerSocket serverSocket=null;
            try {
                serverSocket=new ServerSocket(8688);
            } catch (IOException e) {
                e.printStackTrace();
            }
            while (!isrun)
            {
                try {
                    Socket accept = serverSocket.accept();
                    responseClient(accept);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void responseClient(Socket client)throws IOException
    {
        BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
        PrintWriter printWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(client.getOutputStream())), true);
        printWriter.println("欢迎来到聊天室！");
        while (!isrun)
        {
            String s = reader.readLine();
            if (s==null)
            {

            }
            else
            {
                System.out.println("客户端:"+s);
            }
        }
        reader.close();

    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }


    @Override
    public void onCreate() {
        super.onCreate();
        new Thread(new SocketThread()).start();
    }


}
